// V-backend/src/models/Order.js
module.exports = (sequelize, DataTypes) => {
  const Order = sequelize.define('Order', {
    order_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      field: 'order_id'
    },
    order_number: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      field: 'order_number'
    },
    audience_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      field: 'audience_id'
    },
    total_amount: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      field: 'total_amount'
    },
    status: {
      type: DataTypes.ENUM('pending', 'paid', 'shipped', 'completed', 'cancelled', 'refunded'),
      defaultValue: 'pending',
      field: 'status'
    },
    payment_method: {
      type: DataTypes.STRING(50),
      allowNull: true,
      field: 'payment_method'
    },
    payment_status: {
      type: DataTypes.ENUM('pending', 'paid', 'failed', 'refunded'),
      defaultValue: 'pending',
      field: 'payment_status'
    },
    shipping_address: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'shipping_address'
    },
    recipient_name: {
      type: DataTypes.STRING(100),
      allowNull: true,
      field: 'recipient_name'
    },
    recipient_phone: {
      type: DataTypes.STRING(20),
      allowNull: true,
      field: 'recipient_phone'
    },
    note: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'note'
    },
    paid_at: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'paid_at'
    },
    completed_at: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'completed_at'
    },
    created_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      field: 'created_at'
    }
    // 移除 updated_at 字段
  }, {
    tableName: 'v_order',
    timestamps: false,
    hooks: {
      beforeCreate: (order) => {
        const timestamp = new Date().getTime();
        const random = Math.floor(Math.random() * 1000);
        order.order_number = `ORD${timestamp}${random}`;
      }
    }
  });

  Order.associate = function(models) {
    Order.belongsTo(models.Audience, {
      foreignKey: 'audience_id',
      as: 'audience'
    });
    
    Order.hasMany(models.OrderItem, {
      foreignKey: 'order_id',
      as: 'items'
    });
  };

  return Order;
};